package com.hd.trans.framework.tools;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

/**
 *
 * Author: yang
 * Date: 2019/1/3 11:13
 * Desc: 屏幕适配(今日头条适配方案)
 *
 */
public class ScreenAdaptation {

    // 系统的Density
    private static float sNoncompatDensity;
    // 系统的ScaledDensity
    private static float sNoncompatScaledDensity;

//    private static final float APP_DP = 480.f;//设计稿宽度DP
//    private static final float APP_DP = 360.f;//设计稿宽度DP
    private static final float APP_DP = 375.f;//设计稿宽度DP

    public static void setCustomDensity(Activity activity, Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        if (sNoncompatDensity == 0) {
            sNoncompatDensity = displayMetrics.density;
            sNoncompatScaledDensity = displayMetrics.scaledDensity;

            // 监听在系统设置中切换字体
            context.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sNoncompatScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }

        // 此处以 APP_DP 的设计图作为例子
        float targetDensity = ((float) displayMetrics.widthPixels) / APP_DP;
        Configuration mConfiguration = activity.getResources().getConfiguration(); //获取设置的配置信息
        int ori = mConfiguration.orientation; //获取屏幕方向
        if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
            //横屏
            targetDensity = ((float) displayMetrics.heightPixels) / APP_DP;
        } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
            //竖屏
            targetDensity = ((float) displayMetrics.widthPixels) / APP_DP;
        }

        float targetScaledDensity = targetDensity * (sNoncompatScaledDensity / sNoncompatDensity);
        int targetDensityDpi = (int) (160 * targetDensity);
        displayMetrics.density = targetDensity;
//        displayMetrics.scaledDensity = targetScaledDensity;//改变字体大小
        displayMetrics.scaledDensity = targetDensity;//不改变字体大小
        displayMetrics.densityDpi = targetDensityDpi;

        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
//        activityDisplayMetrics.scaledDensity = targetScaledDensity;//改变字体大小
        activityDisplayMetrics.scaledDensity = targetDensity;//不改变字体大小
        activityDisplayMetrics.densityDpi = targetDensityDpi;


    }

}
